from funasr import AutoModel
from app.utils.logger import setup_logger
from app.config import settings
import os

logger = setup_logger("asr_model")

class ASRModelManager:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(ASRModelManager, cls).__new__(cls)
            cls._instance.model = None
        return cls._instance
    
    async def load_model(self):
        """加载ASR模型"""
        if self.model is not None:
            return self.model

        logger.info("正在加载 FunASR 模型...")
        try:
            # 从配置文件中获取模型路径
            model_path = settings.MODEL_DIR
            self.model = AutoModel(
                model=model_path,
                disable_update=True,
                vad_model="fsmn-vad",
                vad_kwargs={"max_single_segment_time": 30000},
                device=settings.DEVICE if settings.USE_GPU else None,
                hub="hf",
            )
            logger.info("FunASR 模型加载成功")
            return self.model
        except FileNotFoundError:
            logger.error(f"FunASR 模型加载失败: 未找到模型文件 {model_path}")
            raise
        except ImportError:
            logger.error(f"FunASR 模型加载失败: 导入模型依赖失败")
            raise
        except Exception as e:
            logger.error(f"FunASR 模型加载失败: {str(e)}")
            raise
    
    def get_model(self):
        """获取已加载的模型"""
        if self.model is None:
            raise RuntimeError("模型尚未加载，请先调用 load_model() 方法")
        return self.model

# 创建单例实例
asr_model_manager = ASRModelManager()